import os
import json
import shutil


class ConfigManager:
    def __init__(self, config_path=None, sensitive_words_path=None):
        # 获取用户主目录
        user_data_dir = os.path.expanduser("~")
        app_data_dir = os.path.join(user_data_dir, ".aispace_dbg")
        os.makedirs(app_data_dir, exist_ok=True)  # 确保目录存在

        if config_path is None:
            config_path = os.path.join(app_data_dir, "default_config.json")
        if sensitive_words_path is None:
            sensitive_words_path = os.path.join(app_data_dir, "sensitive_words.json")

        self.config_path = config_path
        self.sensitive_words_path = sensitive_words_path
        self.config = {}

        # 项目默认配置路径
        self.default_sensitive_words_path = os.path.join("config", "sensitive_words.json")

    def load_config(self):
        # 加载主配置文件
        if not os.path.exists(self.config_path) or os.path.getsize(self.config_path) == 0:
            print("主配置文件不存在或为空，正在生成默认配置文件...")
            default_config = {
                "faker_locale": "zh_CN",
                "db_connections": {}
            }
            self.save_config(default_config)
        with open(self.config_path, "r", encoding="utf-8") as file:
            self.config = json.load(file)

        # 加载敏感词配置文件
        if not os.path.exists(self.sensitive_words_path) or os.path.getsize(self.sensitive_words_path) == 0:
            print("敏感词配置文件不存在或为空，尝试从默认目录加载...")
            self.load_default_sensitive_words()
        else:
            with open(self.sensitive_words_path, "r", encoding="utf-8") as file:
                self.config["sensitive_words"] = json.load(file)

        return self.config

    def save_config(self, new_config):
        # 保存主配置文件，排除敏感词配置
        config_to_save = {key: value for key, value in new_config.items() if key != "sensitive_words"}
        with open(self.config_path, "w", encoding="utf-8") as file:
            json.dump(config_to_save, file, ensure_ascii=False, indent=4)
        self.config.update(config_to_save)

        # 如果新配置中有敏感词，单独保存敏感词配置
        if "sensitive_words" in new_config:
            self.save_sensitive_words(new_config["sensitive_words"])

    def save_sensitive_words(self, sensitive_words):
        with open(self.sensitive_words_path, "w", encoding="utf-8") as file:
            json.dump(sensitive_words, file, ensure_ascii=False, indent=4)
        self.config["sensitive_words"] = sensitive_words

    def load_default_sensitive_words(self):
        # 检查默认的敏感词文件是否存在
        if os.path.exists(self.default_sensitive_words_path):
            print("从默认目录加载敏感词配置...")
            shutil.copy(self.default_sensitive_words_path, self.sensitive_words_path)
            with open(self.sensitive_words_path, "r", encoding="utf-8") as file:
                self.config["sensitive_words"] = json.load(file)
        else:
            print("默认敏感词文件不存在，生成空白敏感词配置...")
            self.save_sensitive_words([])

    def get_sensitive_words(self):
        if "sensitive_words" not in self.config:
            self.load_config()
        return self.config["sensitive_words"]

    def add_sensitive_word(self, word):
        sensitive_words = self.get_sensitive_words()
        if word not in sensitive_words:
            sensitive_words.append(word)
            self.save_sensitive_words(sensitive_words)

    def remove_sensitive_word(self, word):
        sensitive_words = self.get_sensitive_words()
        if word in sensitive_words:
            sensitive_words.remove(word)
            self.save_sensitive_words(sensitive_words)